/*
 * Copyright (C) 2004, Velocityme Partnership
 * ButtonAction.java
 *
 * Created on 01 September 2004, 09:05
 */

package com.velocityme.www.interfaces;

import com.velocityme.entity.Contactable;
import com.velocityme.entity.Node;
import com.velocityme.entity.Activity;
import com.velocityme.entity.Transition;
import com.velocityme.entity.User;
import com.velocityme.enums.Permission;
import com.velocityme.session.KeyLocal;
import com.velocityme.session.NodeLocal;
import com.velocityme.session.SearchLocal;
import com.velocityme.session.TaskLocal;
import com.velocityme.session.UserLocal;
import com.velocityme.www.actionforms.ButtonActionForm;
import com.velocityme.www.actionforms.ChangeStateActionForm;
import com.velocityme.www.actionforms.ReassignResponsibilityActionForm;
import com.velocityme.www.dto.IdName;
import com.velocityme.www.dto.IntegerString;
import com.velocityme.www.utility.NodeUtil;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author  Robert
 */
public class ButtonAction extends org.apache.struts.action.Action {
    
    /** Creates a new instance of ButtonAction */
    public ButtonAction() {
    }
    
    @Override
    public ActionForward execute(ActionMapping mapping, 
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
    
        try {
            ButtonActionForm buttonActionForm = (ButtonActionForm)form;
            HttpSession session = request.getSession();
            KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
            Long nodeId = (Long)session.getAttribute("nodeId");
            Node node = lookupNodeBean().findNode(key, nodeId);
            if (buttonActionForm.getButton().equals("EditNode")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_NODE_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditSprint")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_SPRINT_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditSystemProperty")) {
                return mapping.findForward("ACTION_SYSTEMPROPERTY_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditContactDetailType")) {
                return mapping.findForward("ACTION_CONTACTDETAILTYPE_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("AddLicence")) {
                return mapping.findForward("ACTION_ADDLICENCE_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditProject")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_PROJECT_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditAnchor")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_ANCHOR_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditAction")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_ACTION_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditIssue")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_ISSUE_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditOrganisation")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_ORGANISATION_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditDepartment")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_DEPARTMENT_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditPerson")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_PERSON_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditUser")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_USER_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditGroup")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_GROUP_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditState")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_STATE_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditStatus")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_STATUS_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditTaskStateMachine")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_TASKSTATEMACHINE_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("StateMachine")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_STATEMACHINE_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditRole")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_ROLE_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("EditNote")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_NOTE_EDIT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("Comment")) {
                return mapping.findForward("ACTION_POST_COMMENT_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("Password")) {
                session.setAttribute("enterOldPassword", new Boolean(!lookupSearchBean().getAssignedPermissions(key, node).contains(Permission.USER_CHANGE_PASSWORD)));
                return mapping.findForward("ACTION_CHANGE_PASSWORD_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("ChangeState")) {
                Activity task = (Activity)node;
                Collection<IdName> idNames = new ArrayList<IdName>();
                TaskLocal taskLocal = lookupTaskBean();
                for (Transition transition: taskLocal.getLegalTransitions(key, nodeId)) {
                    idNames.add(new IdName(transition.getId(), transition.toString()));
                }
                session.setAttribute("transitionPairs", idNames);
                session.setAttribute("completePairs", NodeUtil.getInstance().getPercentageCompletes());
                session.setAttribute("permissionTimeCreate", lookupSearchBean().getAssignedPermissions(key, node).contains(Permission.TIME_CREATE));
                session.setAttribute("years", NodeUtil.getInstance().getYears());
                session.setAttribute("months", NodeUtil.getInstance().getMonths());
                session.setAttribute("days", NodeUtil.getInstance().getDays());
                session.setAttribute("hours", NodeUtil.getInstance().getHours());
                session.setAttribute("durationDays", NodeUtil.getInstance().getDurationDays());
                session.setAttribute("durationHours", NodeUtil.getInstance().getDurationHours());
                session.setAttribute("minutes", NodeUtil.getInstance().getMinutes());
                // setup default values
                Calendar now = Calendar.getInstance();
                ChangeStateActionForm changeStateAF = new ChangeStateActionForm();
                changeStateAF.setPercentageComplete(task.getPercentageComplete());
                changeStateAF.setDurationTotalMins(task.getRemainingDuration_min());
                changeStateAF.setAssignTime(task.getState().isActive());
                changeStateAF.setYear(now.get(Calendar.YEAR));
                changeStateAF.setMonth(now.get(Calendar.MONTH));
                changeStateAF.setDay(now.get(Calendar.DATE));
                Calendar start = Calendar.getInstance();
                start.setTime(taskLocal.getTaskLastStateChangeTime(key, nodeId));
                changeStateAF.setStateId(task.getState().getId());
                changeStateAF.setStartHour(start.get(Calendar.HOUR_OF_DAY));
                changeStateAF.setStartMinute(start.get(Calendar.MINUTE)/5*5);
                changeStateAF.setStopHour(now.get(Calendar.HOUR_OF_DAY));
                changeStateAF.setStopMinute(now.get(Calendar.MINUTE)/5*5);
                session.setAttribute("changeStateActionForm", changeStateAF);
                return mapping.findForward("ACTION_CHANGE_STATE_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("ReassignResponsibility")) {
                Activity task = (Activity)node;
                session.setAttribute("allContactablePairs", NodeUtil.getAllContactablePairs(key));
                Collection<IdName> responsibleContactableIdNames = new ArrayList<IdName>();
                for (Contactable contactable: task.getResponsibleContactables()) {
                    responsibleContactableIdNames.add(new IdName(contactable.getId(), contactable.toString()));
                }
                session.setAttribute("responsibleContactablePairs", responsibleContactableIdNames);
                session.setAttribute("reassignResponsibilityActionForm", new ReassignResponsibilityActionForm());
                return mapping.findForward("ACTION_REASSIGN_RESPONSIBILITY_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("CreateTime")) {
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_CREATE_TIME_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("ToggleUserEnabled")) {
                User user = lookupUserBean().findUser(key, nodeId);
                session.setAttribute("userValue", user);
                return mapping.findForward("ACTION_TOGGLE_USER_ENABLED_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("ToggleUserInterest")) {
                return mapping.findForward("ACTION_TOGGLE_USER_INTERESTED_SUCCESS");
            }
            if (buttonActionForm.getButton().equals("UpdateTime")) {
                lookupTaskBean().recursiveUpdateTimes(key, nodeId);
                request.setAttribute("nodeId", nodeId);
                return mapping.findForward("ACTION_UPDATE_TIME_SUCCESS");
            }
        }
        catch(Exception e){
            request.setAttribute("Additional_Info", e);
        }
        return mapping.findForward("ACTION_BUTTON_FAILED");
    }

    private NodeLocal lookupNodeBean() {
        try {
            Context c = new InitialContext();
            return (NodeLocal) c.lookup("java:comp/env/NodeBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private SearchLocal lookupSearchBean() {
        try {
            Context c = new InitialContext();
            return (SearchLocal) c.lookup("java:comp/env/SearchBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private TaskLocal lookupTaskBean() {
        try {
            Context c = new InitialContext();
            return (TaskLocal) c.lookup("java:comp/env/TaskBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private UserLocal lookupUserBean() {
        try {
            Context c = new InitialContext();
            return (UserLocal) c.lookup("java:comp/env/UserBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
    
}
